import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:async/async.dart';
import 'package:flustars/flustars.dart' as flustars;

class VegetablesStatisticsIndex extends StatefulWidget {
  VegetablesStatisticsIndex({Key key}) : super(key: key);

  @override
  VegetablesStatisticsIndexState createState() => VegetablesStatisticsIndexState();
}

class VegetablesStatisticsIndexState extends State<VegetablesStatisticsIndex> {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();
  DateTime startTime;

  DateTime endTime;

  RefreshController _refreshController;

  List<dynamic> dataList = [];

  //排序 int
  int tableSortType = 1;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);

    final now = DateTime.now();

    startTime = DateUtils.startOfTheDay(now);
    endTime = DateUtils.endOfTheDay(now);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  String dateTime2String(DateTime dateTime) {
    return flustars.DateUtil.formatDate(dateTime);
  }

  //发送邮箱
  sendMailbox(String e) async {
    showLoadingToast();
    try {
      var res = await api.sendEmailCommoditySalesData(
        startTime: dateTime2String(startTime),
        endTime: dateTime2String(endTime),
        email: e ?? '',
        sortType: tableSortType,
      );
      if (res.successful()) {
        toast("邮箱发送成功!");
        Navigator.pop(context);
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //格式化钱
  priceHandle(num) {
    return '¥' + AmountUtil.price2String((num) ?? 0);
  }

  List<TableRow> dataTableTableRow() {
    return (dataList ?? [])
        .map(
          (str) => TableRow(
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                width: 1.px,
                color: ColorConstant.e6e6,
              ))),
              children: [
                TableDataCol("${str["commodity"] ?? '--'}"),
                TableDataCol("${str["menu"] ?? '--'}"),
                TableDataCol("${priceHandle(str["price"] ?? 0)}"),
                TableDataCol("${str["totalCount"] ?? '--'}"),
                TableDataCol("${priceHandle(str["meterialAmount"])}"),
                TableDataCol("${priceHandle(str["totalPrice"])}"),
                TableDataCol("${priceHandle(str["discountAmount"])}"),
                TableDataCol("${priceHandle(str["totalAmount"])}"),
                TableDataCol("${str["rate"] ?? '--'}", rightBorder: false),
              ]),
        )
        .toList();
  }

  Widget TableDataCol(dynamic v, {bool rightBorder = true, TextStyle style}) {
    return v is Widget
        ? v
        : Container(
            decoration: rightBorder == true
                ? BoxDecoration(
                    border: Border(
                        right: BorderSide(
                    width: 1.px,
                    color: ColorConstant.e6e6,
                  )))
                : null,
            padding: EdgeInsets.symmetric(
              vertical: 22.w,
            ),
            child: Center(
              child: Text(
                "$v",
                style: style ?? TextStyleConstant().normal_1_28,
              ),
            ),
          );
  }

  //数据表格
  Widget TableCol(dynamic title) {
    return title is Widget
        ? title
        : Container(
            padding: EdgeInsets.symmetric(
              vertical: 22.w,
            ),
            child: Center(
              child: Text(
                "$title",
                style: TextStyleConstant().normal_2_28,
              ),
            ),
          );
  }

  Widget tableHeaderCol(String content2, {bool sortIcon = false, bool bottomRightBorder = false, List<dynamic> rowIndexArr}) {
    return Container(
      height: 60.w,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                    border: Border(
                  right: bottomRightBorder == true
                      ? BorderSide(
                          width: 1.px,
                          color: ColorConstant.e6e6,
                        )
                      : BorderSide(
                          width: 0,
                          color: Colors.transparent,
                        ),
                )),
                child: GestureDetector(
                  onTap: () async {
                    if (sortIcon == true) {
                      if (tableSortType == rowIndexArr[0]) {
                        tableSortType = rowIndexArr[1];
                      } else {
                        tableSortType = rowIndexArr[0];
                      }
                      setState(() {});

                      loaderPullRefreshKey.currentState.refresh(needMove: true);
                    }
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        "$content2",
                        style: TextStyleConstant().normal_2_28,
                      ),
                      if (sortIcon)
                        SizedBox(
                          width: 2.w,
                        ),
                      if (sortIcon) IconTriangle(topAndDown: tableHeaderColSortIcon(rowIndexArr)),
                    ],
                  ),
                )),
          ),
        ],
      ),
    );
  }

  tableHeaderColSortIcon(
    List<dynamic> rowIndexArr,
  ) {
    if (tableSortType == rowIndexArr[0]) {
      return true;
    }
    if (tableSortType == rowIndexArr[1]) {
      return false;
    }
    return null;
  }

  Widget IconTriangle({
    bool topAndDown,
  }) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          child: Stack(
            children: <Widget>[
              Container(
                width: 26.w,
                height: 16.w,
              ),
              Positioned(
                right: ScreenUtil.instance.setWidth(-10),
                bottom: ScreenUtil.instance.setWidth(-18),
                child: Icon(
                  Icons.arrow_drop_up,
                  size: 46.sp,
                  color: topAndDown == true ? ColorConstant.ff5770f6 : ColorConstant.ff99,
                ),
              ),
            ],
          ),
        ),
        Container(
          child: Stack(
            children: <Widget>[
              Container(
                width: 26.w,
                height: 16.w,
              ),
              Positioned(
                right: ScreenUtil.instance.setWidth(-10),
                bottom: ScreenUtil.instance.setWidth(-18),
                child: Icon(
                  Icons.arrow_drop_down,
                  size: 46.sp,
                  color: topAndDown == false ? ColorConstant.ff5770f6 : ColorConstant.ff99,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget dataTable() {
    return Container(
      margin: EdgeInsets.only(
//        top:28.w,
//        bottom:28.w,
//        left:26.w,
//        right:26.w,
          ),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(
            14.w,
          ),
          boxShadow: [
            BoxShadow(
              color: ColorConstant.shadow,
              spreadRadius: 1.w,
              blurRadius: 9.w,
            )
          ],
        ),
        child: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Expanded(
                child: MScrollbar(
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Column(
                      children: <Widget>[
                        Table(columnWidths: {
                          //列宽
                          0: FixedColumnWidth(96.0),
                          1: FixedColumnWidth(100.0),
                          2: FixedColumnWidth(100.0),
                          3: FixedColumnWidth(100.0),
                          4: FixedColumnWidth(100.0),
                          5: FixedColumnWidth(100.0),
                          6: FixedColumnWidth(100.0),
                          7: FixedColumnWidth(100.0),
                          8: FixedColumnWidth(100.0),
                        }, children: <TableRow>[
                          TableRow(
                              decoration: BoxDecoration(
                                color: Color.fromRGBO(245, 245, 245, 1),
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(14.w),
                                  topRight: Radius.circular(14.w),
                                ),
                              ),
                              children: [
                                tableHeaderCol(
                                  "菜品名称",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "菜品分类",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol("售卖价", bottomRightBorder: true, sortIcon: true, rowIndexArr: [1, 2]),
                                tableHeaderCol("销量", bottomRightBorder: true, sortIcon: true, rowIndexArr: [3, 4]),
                                tableHeaderCol("加料金额", bottomRightBorder: true, sortIcon: true, rowIndexArr: [5, 6]),
                                tableHeaderCol("销售金额", bottomRightBorder: true, sortIcon: true, rowIndexArr: [7, 8]),
                                tableHeaderCol(
                                  "优惠金额",
                                  bottomRightBorder: true,
                                  sortIcon: true,
                                  rowIndexArr: [9, 10],
                                ),
                                tableHeaderCol("应收金额", bottomRightBorder: true, sortIcon: true, rowIndexArr: [11, 12]),
                                tableHeaderCol("点单率", sortIcon: true, rowIndexArr: [13, 14]),
                              ]),
                          ...dataTableTableRow(),
                        ]),
                        SizedBox(
                          height: 12.w,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<Result<List<dynamic>>> _loadTask() {
    Result.value([]);
  }

  Future<Result<List<dynamic>>> _refreshTask() async {
    var res = await api.commoditySalesData(
      startTime: dateTime2String(startTime),
      endTime: dateTime2String(endTime),
      sortType: tableSortType,
    );
    if (res.successful()) {
      dataList = (res.data['voList'] ?? []);

      setState(() {});
      return Result.value([1]);
    } else {
      toast(res.msg);
      return Result.value([]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
        top: 16.w,
      ),
      child: Container(
        padding: EdgeInsets.symmetric(
          horizontal: 28.w,
        ),
        child: Column(
          children: <Widget>[
            CalendarBar(
              startDateTime: startTime,
              endDateTime: endTime,
              onDateTimeChanged: (List<DateTime> dateTime) {
                startTime = dateTime[0];
                endTime = dateTime[1];
                loaderPullRefreshKey.currentState.refresh();
              },
              type: CalendarType.ymdhm,
            ),
            Expanded(
              child: LoaderPullRefresh<dynamic>(
                  key: loaderPullRefreshKey,
                  loadTask: _loadTask,
                  refreshTask: _refreshTask,
                  builder: (context) {
                    return SingleChildScrollView(
                      child: Column(
                        children: <Widget>[
                          SizedBox(
                            height: 30.w,
                          ),
                          dataTable(),
                          SizedBox(
                            height: 20.w,
                          ),
                        ],
                      ),
                    );
                  }),
            ),
          ],
        ),
      ),
    );
  }
}
